//
//  GenderBoxView.swift
//  YouCaiShoppingMall
//
//  Created by 优裁科技 on 2017/11/29.
//  Copyright © 2017年 优裁科技. All rights reserved.
//

import UIKit

/**
 * 下拉选择弹框
 */
class SelectBoxView: UIView {

    private let content_height:CGFloat = 200
    private let content_head_view_height:CGFloat = 50
    private let animation_interval:TimeInterval = 0.35
    private let list_cell_count = 1
    private let k_window:UIWindow = UIApplication.shared.keyWindow!
    
    /** 当前选中的值 */
    private var current_value:String?
    private var current_server_value:String?
    
    /** 标题 */
    var boxTitle:String? {
        didSet{
            self.labBoxTitle.text = boxTitle
        }
    }

    /** 需要传值指定 */
    var dataValues:[String]?
    var dataArr:[String]? {
        didSet{
            self.dataPicker.reloadComponent(0)

            if dataArr != nil {
                self.current_value = dataArr?.first
                self.current_server_value = dataValues?.first
                self.dataPicker.selectRow(0, inComponent: 0, animated: false)
            }
        }
    }
    
    /// 确定回调
    // @params txt 默认取此值
    // @params val 个别需要取此值
    var selectBoxFinish:((_ txt:String?,_ val:String?)->())? = nil


    //MARK: - override func
    override init(frame: CGRect) {
        super.init(frame: frame)

        self.backgroundColor = UIColor.clear
        self.initView()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func updateConstraints() {
        super.updateConstraints()
        
        self.contentView.snp.makeConstraints { make in
            make.left.right.equalTo(0)
            make.height.equalTo(content_height)
            make.bottom.equalTo(-K_APP_SAFETY_HEIGHT)
        }
        
        self.headView.snp.makeConstraints { make in
            make.left.right.equalTo(0)
            make.top.equalTo(0)
            make.height.equalTo(content_head_view_height)
        }
        
        self.btnCancle.snp.makeConstraints { make in
            make.left.top.equalTo(0)
            make.width.equalTo(70)
            make.height.equalTo(content_head_view_height - 1)
        }
        
        self.btnOk.snp.makeConstraints { make in
            make.right.top.equalTo(0)
            make.width.equalTo(70)
            make.height.equalTo(content_head_view_height - 1)
        }
        
        self.dataPicker.snp.makeConstraints { make in
            make.left.right.bottom.equalTo(0)
            make.top.equalTo(content_head_view_height)
        }
        
        self.labBoxTitle.snp.makeConstraints {[weak self] make in
            guard let self = self else { return }
            make.width.equalTo(100)
            make.top.bottom.equalTo(0)
            make.centerX.equalTo(self.snp.centerX)
        }
    }
    
    
    //MARK: - initView
    private func initView(){
        //点击手势
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(tapGestureAction))
        self.addGestureRecognizer(tap)
       
        //轻扫事件
        let swipe = UISwipeGestureRecognizer.init(target: self, action: #selector(swipeGestureAction(sender:)))
        swipe.direction = UISwipeGestureRecognizer.Direction.down
        self.addGestureRecognizer(swipe)
        
        self.addSubview(self.contentView)
        self.contentView.addSubview(self.headView)
        self.headView.addSubview(self.btnCancle)
        self.headView.addSubview(self.btnOk)
        self.headView.addSubview(self.labBoxTitle)
        self.contentView.addSubview(self.dataPicker)
        
        if dataArr != nil {
            current_value = dataArr?.first
            current_server_value = dataValues?.first
        }
        
        setNeedsUpdateConstraints()
    }
    
    //更新信息
    func reloadData(strValue:String){
        //设置对应的选项
        var index:Int? =  dataArr?.firstIndex(where: {return $0 == strValue})
        if index == nil {
            index = 0
        }
        
        dataPicker.selectRow(index!, inComponent: 0, animated: true)
    }
    
    
    //MARK: - 按钮点击
    @IBAction private func btnAction(sender:UIButton) {
        if sender == self.btnOk {
            self.selectBoxFinish?(self.current_value,self.current_server_value)
        }
        else {
            self.selectBoxFinish?(nil,nil)
        }
       
        self.hideBoxView()
    }


    //MARK: - 轻扫手势
    @objc private func swipeGestureAction(sender:UISwipeGestureRecognizer) {
        if sender.direction == .down {
            self.hideBoxView()
            self.selectBoxFinish?(nil,nil)
        }
    }
    
    //MARK: - 点击手势
    @objc private func tapGestureAction(sender:UITapGestureRecognizer) {
        self.hideBoxView()
        self.selectBoxFinish?(nil,nil)
    }

    
    //MARK: - 显示视图
    /** 显示视图 */
    func showBoxView(){

        //关闭当前键盘
        self.endEditing(true)
        UIApplication.shared.keyWindow?.endEditing(true)
        
        if !k_window.subviews.contains(self) {
            k_window.addSubview(self)
            
            self.contentView.y = K_APP_WIDTH
            UIView.animate(withDuration: animation_interval, animations: {
                //self.contentView.alpha = 1
                self.contentView.y = K_APP_HEIGHT - self.content_height - K_APP_SAFETY_HEIGHT
            }) { (finished:Bool) in
                self.layer.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.3).cgColor
            }
        }
    }
    
    /** 移除视图 */
    func hideBoxView(){
        
        if k_window.subviews.contains(self) {
            
            UIView.animate(withDuration: animation_interval, animations: {
                self.contentView.y = K_APP_HEIGHT
            }) { (finished:Bool) in
                //self.contentView.alpha = 0
                self.dataArr = nil
                self.layer.backgroundColor = UIColor.clear.cgColor
                self.removeFromSuperview()
                print("视图已移除")
            }
        }
    }

    
    //MARK: - lazy load
    private lazy var contentView:UIView = {
        let _v = UIView.init()
        _v.backgroundColor = K_APP_CELL_BGCOLOR
        //_v.alpha = 0
        
        return _v
    }()
    
    private lazy var headView:UIView = {
        let _v = UIView.init()
        
        //底部线
        let h:CGFloat = 0.3
        let y = content_head_view_height - h
        let _l = UIView.init(frame: CGRect.init(x: 0, y: y, width: K_APP_WIDTH, height: h))
        _l.backgroundColor = UIColor.init().colorFromHexString(hex: "#E5E5E5")
        _v.addSubview(_l)
        
        return _v
    }()
    
    private lazy var btnCancle:UIButton = {
        let _b = UIButton.init(type: .custom)
        _b.backgroundColor = UIColor.clear
        _b.contentHorizontalAlignment = .center
        
        _b.setTitle("取消", for: .normal)
        _b.setTitleColor(UIColor.gray, for: .normal)
        _b.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        _b.addTarget(self, action: #selector(btnAction(sender:)), for: .touchUpInside)
        
        return _b
    }()
    
    private lazy var btnOk:UIButton = {
        let _b = UIButton.init(type: .custom)
        _b.backgroundColor = UIColor.clear
        _b.contentHorizontalAlignment = .center
        
        _b.setTitle("确定", for: .normal)
        _b.setTitleColor(UIColor.init().colorFromHexString(hex: "#4B72E5"), for: .normal)
        _b.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        _b.addTarget(self, action: #selector(btnAction(sender:)), for: .touchUpInside)
        
        return _b
    }()
    
    private lazy var dataPicker:UIPickerView = {
        let _dataPicker = UIPickerView.init()
        _dataPicker.backgroundColor = UIColor.clear
        _dataPicker.delegate = self
        _dataPicker.dataSource = self
        _dataPicker.tintColor = UIColor.black
        
        return _dataPicker
    }()
    
    private lazy var labBoxTitle:YYLabel = {
        let _lab = YYLabel.init()
        _lab.textColor = K_APP_BOXVIEW_TITLE_COLOR
        _lab.textAlignment = .center
        _lab.font = UIFont.boldSystemFont(ofSize: 16)
        
        return _lab
    }()
}


//MARK: - extension
extension SelectBoxView : UIPickerViewDelegate,UIPickerViewDataSource {
    //MARK: UIPickerViewDelegate,UIPickerViewDataSource
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return list_cell_count
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if dataArr != nil {
            return dataArr!.count
        }

        return 0
    }

    func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
        return self.frame.size.width
    }

    func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
        return 34
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return dataArr?[row]
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if dataArr != nil && dataArr!.count > row {
            current_value = dataArr?[row]
            current_server_value = (dataValues != nil && dataValues!.count > row) ? dataValues![row] : dataValues?.first
        }
    }
}

